﻿/*************************************************************************************
 * 文 件 名:   HK_MakeGroup
 * 
 * 描    述:   对选中的物体进行打组操作
 * 
 * 版    本：  V1.0
 * 创 建 者：  京产肠饭
 * 创建时间：  2021/8/25
 * 链   接：  https://gitee.com/JingChanChangFan/hk_-unity-tools
*************************************************************************************/

using UnityEditor;
using UnityEngine;

[InitializeOnLoad]
public class HK_MakeGroup
{
    static HK_MakeGroup()
    {
        HK_ToolSetting.ChangeMakeGroupEvent += OnChangeMakeGroupEvent;
    }

    static void OnChangeMakeGroupEvent(bool _isEnable)
    {
        isEnable = _isEnable;
    }

    static bool isEnable = true;

    [MenuItem("HKTools/MakeGroup %g", true, 12)]
    static bool MakeGroupValidate()
    {
        return isEnable;
    }

    [MenuItem("HKTools/MakeGroup %g", false, 12)]
    public static void MakeGroup()
    {
        if (Selection.gameObjects.Length == 0)
        {
            Debug.Log("<color=red>错误: 未选中物体，无法执行打组操作</color>");
            return;
        }

        GameObject go = new GameObject();

        Undo.RegisterCreatedObjectUndo(go, "CreateParent");

        go.name = "Parent_Go";

        Vector3 pos = Vector3.zero;

        foreach (var item in Selection.gameObjects)
        {
            pos += item.transform.position;
        }

        pos = pos / Selection.gameObjects.Length;

        go.transform.position = pos;

        foreach (var item in Selection.gameObjects)
        {
            Undo.SetTransformParent(item.transform, go.transform, "SetParent");
        }

        Selection.activeGameObject = null;
    }
}
